<template>
    <div class="upload-main" id="upload-main">
        <el-dialog title="上传视频" size="small" v-model="showPopover" @close="handleHidePopover" class="el-title">

            <div class="upload-img-list">
              <div class="upload-img-item" v-model="files" v-for="(item,index) in files">
                <div class="upload-operator" v-if='item.show == false && item.ashow'>
                  <span class="iconfont icon-review" @click="handlePictureCardPreview(item)"></span>
                  <span class="iconfont icon-del" @click="handleRemove(item.id,item.key,item.persistentId)"></span>
                </div>
                <div class="upload-mask"  v-if='item.show == false && item.ashow'>      
                </div>
                <div class="item-id"></div>

                <div v-if="item.percent!=100 && item.show!=true" class="mdl-progress mdl-js-progress mdl-progress__indeterminate is-upgraded" data-upgraded=",MaterialProgress"
                >
                    <div class="progressbar bar bar1" :style="{width:item.percent}"></div>
                    <div class="bufferbar bar bar2" style="width: 100%;"></div>
                    <div class="auxbar bar bar3" style="width: 0%;"></div>
                </div>

                <div v-if='item.show == true'style="text-align: center;margin-top: 26px;">
                  <img style="width:12px;height:12px;display: inline-block" src="../../assets/img/Combined Shape Copy 2.png">
                  <span style="color: #F70000;font-size: 12px;margin-left: 2px;text-align: center">上传失败</span>
                </div>
                
               <img v-if="item.preViewUrl!=null" :index='index' v-lazy="item.preViewUrl" />
              </div>


              <div id="upload-video-handler-container">
                <div id="upload-video-handler" style="cursor: pointer;">
                    <span class="iconfont icon-create-adv"></span>
                    <span class="up-txt">上传视频</span>
                </div>
                <!--div class="desc">*可拖拽或本地上传多张图片</div-->
              </div>
            </div>

            <div slot="footer" >
                <div class="btn_common_white btn_common_small " @click="handleHidePopover">取消</div>
                <div :class="(files.length > 0 && upnumberSeccess) ? 'btn_common_yellow':'btn_common_grey_disable'" class="btn_common_small btn-common"  @click="submitUpload">上传</div>
            </div>
        </el-dialog>
        <el-dialog v-model="dialogVisible" size="tiny">
            <loading v-if='loadingShows' :customClass="customLoading" />
          <video  v-if='showVideo' :src="dialogImageUrl" controls="controls" preload="auto" id='video1'
          width='960px;' height="540px">
          您的浏览器不支持 video 标签。
          </video>
        </el-dialog>
    </div>
</template>
<script>
    import Vue from 'vue'
    import { getCookie } from '~/assets/js/global';
    import {SHOW_POPOVER_UPLOAD_IMG} from '~/store/mutation-types/upload'
    import { mapGetters } from 'Vuex'
    import { Dialog,  Button, Message} from 'element-ui'
    import loading from '~components/loading.vue';
    import { basicConfig } from '~/assets/js/config'
    Vue.use(Dialog);
    Vue.use(Button);

    export default{
        data(){
            return{
                customLoading : 'position:absolute;',
                files : [],
                dialogImageUrl: '',
                dialogVisible: false,
                loadingShows: true,
                showVideo: true,
                loginToken: '',
                upnumberSeccess: false,
            }
        },
        components:{
          loading
        },
        methods: {

          handleHidePopover() {
            this.files = []
            this.uploader.files = []
            this.upnumberSeccess = false
              this.$store.commit('SHOW_POPOVER_UPLOAD_VIDEO',{showPopoverUploadVideo: false});
          },

          handleRemove(id,key,persistentId) {
              this.$store.dispatch("deleteAddVideoKey",{  
                  key:key,
                  persistentId:persistentId
                  }).then(res=>{
                   
                })
              this.files.forEach((n,i)=>{
                if(n.id == id){
                  this.files.splice(i,1);
                  this.uploader.files.splice(i,1)
                  return;
                }
              });
          },
          handlePictureCardPreview(file) {
            this.showVideo = false
            Vue.nextTick(()=>{
              this.showVideo = true
              this.dialogImageUrl = file.videoUrl;
              this.dialogVisible = true;
               this.loadingShows = true
                    setTimeout(()=>{
                      var video = document.getElementById("video1")
                      video.addEventListener('playing',()=>{
                              this.loadingShows = false
                          })
                      video.addEventListener('canplay',()=>{
                              this.loadingShows = false
                          })
                    },0)
            })
           
          },

          submitUpload(){
            if (this.files.length>0 && this.upnumberSeccess) {
               this.$parent['uploadVideoSuccess'](this.files);
              this.$store.commit('SHOW_POPOVER_UPLOAD_VIDEO',{showPopoverUploadVideo: false});
              this.files = []
              this.uploader.files = []
              this.upnumberSeccess = false
            }
            
          },

        　renderQiniuUpload(){
            //this.renderFlag = true;
            let _this = this;
            this.uploader = Qiniu.uploader({
              runtimes: 'html5,flash,html4',   
              browse_button: 'upload-video-handler',
              multi_selection : true,
              uptoken_url: basicConfig.baseUrl+'/assets/video/upToken.do?loginToken='+this.loginToken,
              //uptoken : '9svFtGE3GS1TCt5pG7wTNxWfYosWeKVEBCAGmMN_:7CKw5d_tHEUsJX4UgQgZObIS_lk=:eyJzY29wZSI6InRlc3QiLCJyZXR1cm5Cb2R5Ijoie1wibmFtZVwiOiQoZm5hbWUpLFwia2V5XCI6JChrZXkpfSIsImRlYWRsaW5lIjoxNDk0MzgzMzE5fQ==',
              filters : {
                  max_file_size : '10mb',
                  prevent_duplicates: true,
                  mime_types: [
                      {title : "Video files", extensions : "mp4"}
                  ]
              },
              domain: 'ads.onloon.net',  
              get_new_uptoken: false,
              container: 'upload-video-handler-container',
              max_file_size: '10mb',
              max_retries: 2,
              dragdrop: true,
              drop_element: 'upload-video-handler-container',
              chunk_size: '4mb',
              auto_start: true,
              save_key:true,
              unique_names: true,
              init: {
                  'FilesAdded': function(up, files) {
                    plupload.each(files, function(file) {
                        up.files = []
                        _this.files = []
                        _this.files.push(file)//视频只能上传一个，清空处理
                    });
                  },

                  'BeforeUpload': function(up, file) {
                     

                  },
                  'UploadProgress': function(up, file) {
                         // 每个文件上传时,处理相关的事情
                  },
                  'FileUploaded': function(up, file, info) {
                    _this.$Lazyload.$off('loaded')
                    _this.$Lazyload.$off('error')
                    _this.$Lazyload.$on('loaded', _this.handel1)
                    let domain = up.getOption('domain');
                    let res = JSON.parse(info);
                    let url = domain + res.persistentId;
                    setTimeout(function () {
                      _this.files.forEach((n,i)=>{
                      if(n.id == file.id){
                        _this.$store.dispatch("getUrlByKeyVideo",{  
                            key:res.key,
                            persistentId:res.persistentId
                            }).then(ress=>{
                              _this.upnumberSeccess = true
                              file.preViewUrl = ress.data.data.preViewUrl;
                              file.videoUrl =  ress.data.data.videoUrl;
                              file.key = res.key;
                              file.show = false
                              file.persistentId = res.persistentId;
                              _this.files.splice(i,1,file);//updated
                              return;
                          })
                        
                      }
                    });
                    },1000)
                    

                    //_this.success(_this.files);
                  },
                  'Error': function(up, err, errTip) {
                    err.file.show = true
                    if (err.code == -601) {
                      Message({
                        duration: 5000,
                        message: '请上传MP4格式的视频',
                        type: 'error',
                      })
                    }
                    if (err.code == -600) {
                      Message({
                        duration: 5000,
                        message: 视频不能大于10M,
                        type: 'error',
                      })
                    }
                    if (err.code == -602 ) {
                      Message.error('请不要重复上传');
                    }
                  },
                  'UploadComplete': function(up, file) {
                  },
                  'Key': function(up, file) {
                      var key = "";
                      return key
                  }
              }
            });


          },

          beforeUpload(file){
          },
          handel1({el, naturalHeight, naturalWidth, $parent, src, loading, error, }, formCache) {
                if (el.attributes['index']) {
                  var index = el.attributes['index'].value
                  if (this.files) {
                    Vue.set(this.files[index],'ashow',true)
                  }
                  
                }
          },
        },

        updated(){
           /*保证初始化一次*/
           !this.uploader && this.renderQiniuUpload();
        },
        computed:{
            ...mapGetters({
                  'showPopover': 'getShowPopoverUploadVideo'
            })
        },
        created() {
        },
        mounted() {
          this.$Lazyload.$off('loaded');
          this.$Lazyload.$off('error');
          this.$Lazyload.$on('loaded', this.handel);
          this.$Lazyload.$on('error', this.handel);
          this.loginToken = getCookie('token');
        },
    }
</script>

<style lang="scss">

    .upload-main{
    .el-dialog--tiny {
      width: auto!important;
    }
    .el-input {
        width: 172px;
        height: 28px;
    }
    .btn-common {
        margin-left: 10px;
    }

    .dialog-footer {
        border-top: 1px solid #EAEEF0;
        padding-top: 15px;
    }
    .el-dialog--small{
        width: 801px;
    }
    .btn_common_white:hover {
      background-color: #EAEEF0;
    }

    .el-dialog__header{
        border-bottom:1px #EAEEF0 solid;
    }


    #upload-video-handler-container {
        position:relative;
        border-radius: 4px;
        height: 90px;
        /*margin-left:340px;*/
        display: inline-block;
        background-color: #f3f7fa;
        border:1px #d7dee4 dashed;
        .desc{
            position:absolute;
            bottom:-25px;
            left: -45px;
            display: block;
            width: 200px;
        }
        &:hover {
          border-color: #20a0ff;
        }
    }
    .upload-operator{
        width: 78px;
        height: 78px;
        position:absolute;
        left:6px;
        top:6px;
        display: none;
        vertical-align: middle;
        padding-top:28px;
        height: 50px;
        z-index: 100;
        span{
            color:#fff;
            font-size:16px;
            margin-left: 13px;
            display: inline-block;
            vertical-align: middle;
            cursor: pointer;
        }
    }
    .upload-mask {
      z-index: 10;
      width: 78px;
      height: 78px;
      position:absolute;
      left:6px;
      top:6px;
      display: none;
      vertical-align: middle;
      padding-top:28px;
      height: 50px;
      background-color:#000;
      opacity: .3;
    }
    .upload-mask:hover {
      display: block;
    }
    .upload-img-item:hover .upload-mask {
        display: block;
    }
    #upload-video-handler{
        padding-top:20px;
        width: 90px;
        height: 70px;
        text-align: center;
    }

    .up-txt{
        display: block;
        text-align: center;
    }

    .el-dialog--small .el-dialog__body{
        height: 300px;
        overflow-y: auto;
    }

    .upload-img-list{
        display: flex;
        flex-wrap:wrap;
    }
    .upload-img-item{
        position:relative;
        width: 78px;
        height:78px;
        padding:6px;
        border:1px #D5DFE4 solid;
        border-radius: 4px;
        margin: 0 14px 14px 0;
    // img{
    //     display: block;
    //     width: 78px;
    //     height: 78px;
    //     border-radius: 4px;
    // }
    img[lazy=loaded]{
      display: block;
      width: 78px;
      height: 78px;
      border-radius: 4px;
    }
    img[lazy=loading] {
        height: 18px!important;
        width: 18px!important;
        position: absolute;
        left: 50%;
        top: 50%;
        transform:translate(-50%,-50%);
      }
      img[lazy=error] {
        height: 18px!important;
        width:24px!important;
        position: absolute;
        left: 50%;
        top: 50%;
        transform:translate(-50%,-50%);
      }
    }

    .item-id{
        position:absolute;
    }
    .mdl-progress {
        display: block;
        position: absolute;
        top:40px;
        height: 6px;
        width: 76px;
        max-width: 100%
    }

    .mdl-progress>.bar {
        display: block;
        position: absolute;
        top: 0;
        bottom: 0;
        width: 0%;
        transition: width .2s cubic-bezier(.4,0,.2,1)
    }

    .mdl-progress>.progressbar {
        background-color: #fffaea;
        z-index: 1;
        left: 0
    }

    .mdl-progress>.bufferbar {
        /*background-image: linear-gradient(to right,rgba(255,255,255,.7),rgba(255,255,255,.7)),linear-gradient(to right,#3f51b5 ,#3f51b5);*/
        border: 1px #ffb100 solid;
        border-radius:8px;
        background-color:#fffaea;
        z-index: 0;
        left: 0
    }

    .mdl-progress>.auxbar {
        right: 0;
        height: 6px;
    }

    @supports (-webkit-appearance: none) {
        .mdl-progress:not(.mdl-progress--indeterminate):not(.mdl-progress--indeterminate)>.auxbar,.mdl-progress:not(.mdl-progress__indeterminate):not(.mdl-progress__indeterminate)>.auxbar {
            /*background-image:linear-gradient(to right,rgba(255,255,255,.7),rgba(255,255,255,.7)),linear-gradient(to right,#3f51b5 ,#3f51b5);*/
            padding-top:1px;
            height: 5px;
            border-radius:none;
            -webkit-mask: url("");
            mask: url("")
        }
    }

    .mdl-progress:not(.mdl-progress--indeterminate)>.auxbar,.mdl-progress:not(.mdl-progress__indeterminate)>.auxbar {
        /*background-image: linear-gradient(to right,rgba(255,255,255,.9),rgba(255,255,255,.9)),linear-gradient(to right,#3f51b5 ,#3f51b5)*/
        background-color: transparent;
    }

    .mdl-progress.mdl-progress--indeterminate>.bar1,.mdl-progress.mdl-progress__indeterminate>.bar1 {
        -webkit-animation-name: indeterminate1;
        animation-name: indeterminate1
    }

    .mdl-progress.mdl-progress--indeterminate>.bar1,.mdl-progress.mdl-progress__indeterminate>.bar1,.mdl-progress.mdl-progress--indeterminate>.bar3,.mdl-progress.mdl-progress__indeterminate>.bar3 {

        -webkit-animation-duration: 2s;
        animation-duration: 2s;
        -webkit-animation-iteration-count: infinite;
        animation-iteration-count: infinite;
        -webkit-animation-timing-function: linear;
        animation-timing-function: linear
    }

    .mdl-progress__indeterminate .bar1{
        border-radius:8px;
        background-color: #e80;
    }

    .mdl-progress.mdl-progress--indeterminate>.bar3,.mdl-progress.mdl-progress__indeterminate>.bar3 {

        background-image: none;
        -webkit-animation-name: indeterminate2;
        animation-name: indeterminate2
    }

    @-webkit-keyframes indeterminate1 {
        0% {
            left: 0%;
            width: 0%
        }

        50% {
            left: 25%;
            width: 75%
        }

        75% {
            left: 100%;
            width: 0%
        }
    }

    @keyframes indeterminate1 {
        0% {
            left: 0%;
            width: 0%
        }

        50% {
            left: 25%;
            width: 75%
        }

        75% {
            left: 100%;
            width: 0%
        }
    }

    @-webkit-keyframes indeterminate2 {
        0%,50% {
            left: 0%;
            width: 0%
        }

        75% {
            left: 0%;
            width: 25%
        }

        100% {
            left: 100%;
            width: 0%
        }
    }

    @keyframes indeterminate2 {
        0%,50% {
            left: 0%;
            width: 0%
        }

        75% {
            left: 0%;
            width: 25%
        }

        100% {
            left: 100%;
            width: 0%
        }
    }

    }
</style>
